package com.shuwang.user.controller;

import com.shuwang.user.domain.*;
import com.shuwang.user.enums.SigninTypeEnums;
import com.shuwang.user.exception.BadRequestExitException;
import com.shuwang.user.exception.ConflictException;
import com.shuwang.user.exception.ForbiddenException;
import com.shuwang.user.exception.NotFoundException;
import com.shuwang.user.mapper.ShopInfoMapper;
import com.shuwang.user.mapper.UserSigninMapper;
import com.shuwang.user.model.ShopInfo;
import com.shuwang.user.model.ShopInfoExample;
import com.shuwang.user.model.UserSignin;
import com.shuwang.user.model.UserSigninExample;
import com.shuwang.user.until.IDBuilder;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/6/5 0005.
 */

@RestController
@RequestMapping(value = "usersignin")
@Api(value = "user_signin",description = "用户注册API")
public class UserSigninController {

    protected final Logger log = LoggerFactory.getLogger(getClass());  //打日志用的

    @Autowired
    private UserSigninMapper userSigninMapper;

    @Autowired
    private ShopInfoMapper shopInfoMapper;

    @RequestMapping(value = "signinuser",method = RequestMethod.POST)
    @ApiOperation(value = "用户注册接口")
    public UserSigninResponse createUserInfoController (@ApiParam(value = "请输入用户实体类")@Valid @RequestBody UserSigninRequest request){

        UserSigninExample example = new UserSigninExample();
        example.createCriteria().andAccountEqualTo(request.getAccount());
        if ( !userSigninMapper.selectByExample(example).isEmpty() ){
            log.debug("账号已存在");
            throw new ConflictException("账号已存在");
        }

        UserSigninExample example1 = new UserSigninExample();
        example1.createCriteria().andPhoneEqualTo(request.getPhone());
        if ( !userSigninMapper.selectByExample(example1).isEmpty()){
            log.debug("手机号码已被注册");
            throw new ConflictException("手机号码已被注册");
        }

        UserSigninExample example2 = new UserSigninExample();
        example2.createCriteria().andNicknameEqualTo(request.getNickname());
        if ( !userSigninMapper.selectByExample(example2).isEmpty()){
            log.debug("昵称已存在");
            throw new ConflictException("昵称已存在");
        }

        Date getToday = new Date();
        Long userId = IDBuilder.CreateAnyId("202");
        UserSignin userSignin = new UserSignin();

        if ( !request.getRepassword().equals(request.getPassword()) ){
            log.debug("密码输入错误");
            throw new ForbiddenException("密码输入错误");
        }

        BeanUtils.copyProperties(request,userSignin);
        userSignin.setUserId(userId);
        userSignin.setCreateTime(getToday);
        userSignin.setAuthority(SigninTypeEnums.user.getValue());
        userSigninMapper.insertSelective(userSignin);

        UserSignin success = userSigninMapper.selectByPrimaryKey(userSignin.getUserId());
        if (success == null){
            log.debug("用户注册失败");
            throw new NotFoundException("用户注册失败");
        }

        UserSigninResponse response = new UserSigninResponse();
        BeanUtils.copyProperties(success,response);
        response.setAuthority(SigninTypeEnums.user.getName());
        return response;
    }

    @RequestMapping(value = "signinshop",method = RequestMethod.POST)
    @ApiOperation(value = "商铺注册接口")
    public ShopSigninResponse createShopInfoController(@ApiParam(value = "请输入商铺的实体类")@Valid @RequestBody ShopSigninRequest request){


        UserSigninExample example = new UserSigninExample();
        example.createCriteria().andAccountEqualTo(request.getAccount());
        if ( !userSigninMapper.selectByExample(example).isEmpty() ){
            log.debug("账号已存在");
            throw new ConflictException("账号已存在");
        }

        UserSigninExample example1 = new UserSigninExample();
        example1.createCriteria().andPhoneEqualTo(request.getPhone());
        if ( !userSigninMapper.selectByExample(example1).isEmpty()){
            log.debug("手机号码已被注册");
            throw new ConflictException("手机号码已被注册");
        }

        UserSigninExample example2 = new UserSigninExample();
        example2.createCriteria().andNicknameEqualTo(request.getNickname());
        if ( !userSigninMapper.selectByExample(example2).isEmpty()){
            log.debug("昵称已存在");
            throw new ConflictException("昵称已存在");
        }

        Date getToday = new Date();
        Long userId = IDBuilder.CreateAnyId("202");
        Long shopId = IDBuilder.CreateAnyId("203");
        UserSignin userSignin = new UserSignin();
        ShopInfo shopInfo = new ShopInfo();

        ShopInfoExample example3 = new ShopInfoExample();
        example3.createCriteria().andShopNameEqualTo(request.getShopName());
        if ( !shopInfoMapper.selectByExample(example3).isEmpty()){
            log.debug("商铺名已存在");
            throw new ConflictException("商铺名已存在");
        }

        if ( !request.getRepassword().equals(request.getPassword()) ){
            log.debug("密码输入错误");
            throw new ForbiddenException("密码输入错误");
        }

        BeanUtils.copyProperties(request,userSignin);
        userSignin.setUserId(userId);
        userSignin.setCreateTime(getToday);
        userSignin.setAuthority(SigninTypeEnums.shop.getValue());
        userSigninMapper.insertSelective(userSignin);
        BeanUtils.copyProperties(request,shopInfo);
        shopInfo.setShopId(shopId);
        shopInfo.setUserId(userId);
        shopInfoMapper.insertSelective(shopInfo);

        UserSignin usersuccess = userSigninMapper.selectByPrimaryKey(userSignin.getUserId());
        ShopInfo shopsucccess = shopInfoMapper.selectByPrimaryKey(shopInfo.getShopId(),shopInfo.getUserId());
        if (shopsucccess == null || usersuccess == null){
            log.debug("商铺注册失败");
            throw new NotFoundException("商铺注册失败");
        }

        ShopSigninResponse response = new ShopSigninResponse();
        BeanUtils.copyProperties(usersuccess,response);
        BeanUtils.copyProperties(shopsucccess,response);
        response.setAuthority(SigninTypeEnums.shop.getName());
        return response;
    }


    @RequestMapping(value = "signinadministrator",method = RequestMethod.POST)
    @ApiOperation(value = "管理员注册接口")
    public UserSigninResponse createAdministratorController (@ApiParam(value = "请输入用户实体类")@Valid @RequestBody UserSigninRequest request){

        UserSigninExample example = new UserSigninExample();
        example.createCriteria().andAccountEqualTo(request.getAccount());
        if ( !userSigninMapper.selectByExample(example).isEmpty() ){
            log.debug("账号已存在");
            throw new ConflictException("账号已存在");
        }

        UserSigninExample example1 = new UserSigninExample();
        example1.createCriteria().andPhoneEqualTo(request.getPhone());
        if ( !userSigninMapper.selectByExample(example1).isEmpty()){
            log.debug("手机号码已被注册");
            throw new ConflictException("手机号码已被注册");
        }

        Date getToday = new Date();
        Long userId = IDBuilder.CreateAnyId("204");
        UserSignin userSignin = new UserSignin();

        if ( !request.getRepassword().equals(request.getPassword()) ){
            log.debug("密码输入错误");
            throw new ForbiddenException("密码输入错误");
        }

        BeanUtils.copyProperties(request,userSignin);
        userSignin.setUserId(userId);
        userSignin.setCreateTime(getToday);
        userSignin.setAuthority(SigninTypeEnums.administrator.getValue());
        userSigninMapper.insertSelective(userSignin);

        UserSignin success = userSigninMapper.selectByPrimaryKey(userSignin.getUserId());
        if (success == null){
            log.debug("用户注册失败");
            throw new NotFoundException("用户注册失败");
        }

        UserSigninResponse response = new UserSigninResponse();
        BeanUtils.copyProperties(success,response);
        response.setAuthority(SigninTypeEnums.administrator.getName());
        return response;
    }

    @RequestMapping(value = "signinadministrator/load",method = RequestMethod.POST)
    @ApiOperation(value = "管理员登录接口")
    public UserSigninResponse administratorLoadController(@ApiParam(value = "请输入管理员登录实体类") @RequestBody LoadRequest request){

        UserSigninExample example = new UserSigninExample();
        example.createCriteria().andAccountEqualTo(request.getAccount());
        List<UserSignin> userSignins = userSigninMapper.selectByExample(example);

        if (userSignins.isEmpty()){
            log.debug("用户不存在");
            throw new NotFoundException("用户不存在");
        }

        if ( !request.getPassword().equals(userSignins.get(0).getPassword()) ){
            log.debug("密码错误");
            throw new BadRequestExitException("密码错误");
        }

        if ( !userSignins.get(0).getAuthority().equals(SigninTypeEnums.administrator.getValue())){
            log.debug("权限不足");
            throw new ForbiddenException("权限不足");
        }

        UserSigninResponse response = new UserSigninResponse();
        BeanUtils.copyProperties(userSignins.get(0),response);
        response.setAuthority(SigninTypeEnums.administrator.getName());
        return response;
    }

    @RequestMapping(value = "signin/user/{userId}",method = RequestMethod.GET)
    @ApiOperation(value = "根据userId查询用户或管理员信息")
    public UserSigninResponse viewInfoByUserId(@ApiParam(value = "请输入userId")@PathVariable Long userId){

        UserSigninResponse response = new UserSigninResponse();
        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(userId);
        if (userSignin == null){
            log.debug("用户不存在");
            throw new NotFoundException("用户不存在");
        }

        if (userSignin.getAuthority().equals(SigninTypeEnums.user.getValue())){
            response.setAuthority(SigninTypeEnums.user.getName());
        } else if (userSignin.getAuthority().equals(SigninTypeEnums.administrator.getValue())){
            response.setAuthority(SigninTypeEnums.administrator.getName());
        }

        BeanUtils.copyProperties(userSignin,response);
        return response;
    }

    @RequestMapping(value = "signin/shop/{userId}",method = RequestMethod.GET)
    @ApiOperation(value = "根据userId查询商铺信息")
    public ShopSigninResponse viewShopByUserId(@ApiParam(value = "请输入userId")@PathVariable Long userId){

        ShopSigninResponse response = new ShopSigninResponse();
        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(userId);
        ShopInfoExample example = new ShopInfoExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<ShopInfo> shopInfo = shopInfoMapper.selectByExample(example);

        if (userSignin == null || shopInfo.isEmpty()){
            log.debug("商铺不存在");
            throw new NotFoundException("商铺不存在");
        }

        BeanUtils.copyProperties(userSignin,response);
        BeanUtils.copyProperties(shopInfo.get(0),response);
        response.setAuthority(SigninTypeEnums.shop.getName());
        return response;
    }

    @RequestMapping(value = "signin/userinfo/{nickname}",method = RequestMethod.GET)
    @ApiOperation(value = "根据nickname查询用户或管理员信息")
    public UserSigninResponse viewInfoByNickmane(@ApiParam(value = "请输入nickname")@PathVariable String nickname){

        UserSigninResponse response = new UserSigninResponse();
        UserSigninExample example = new UserSigninExample();
        example.createCriteria().andNicknameEqualTo(nickname);
        List<UserSignin> userSignin = userSigninMapper.selectByExample(example);

        if (userSignin == null){
            log.debug("用户不存在");
            throw new NotFoundException("用户不存在");
        }

        if (userSignin.get(0).getAuthority().equals(SigninTypeEnums.user.getValue())){
            response.setAuthority(SigninTypeEnums.user.getName());
        } else if (userSignin.get(0).getAuthority().equals(SigninTypeEnums.administrator.getValue())){
            response.setAuthority(SigninTypeEnums.administrator.getName());
        }

        BeanUtils.copyProperties(userSignin.get(0),response);
        log.info("response{}",response);
        return response;
    }

    @RequestMapping(value = "signin/shopinfo/{shopname}",method = RequestMethod.GET)
    @ApiOperation(value = "根据shopname查询商铺信息")
    public ShopSigninResponse viewShopByNickname(@ApiParam(value = "请输入shopname")@PathVariable String shopname){

        ShopSigninResponse response = new ShopSigninResponse();

        ShopInfoExample shopInfoExample = new ShopInfoExample();
        shopInfoExample.createCriteria().andShopNameEqualTo(shopname);
        List<ShopInfo> shopInfo = shopInfoMapper.selectByExample(shopInfoExample);

        if (shopInfo.isEmpty()){
            log.debug("商铺不存在");
            throw new NotFoundException("商铺不存在");
        }

        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(shopInfo.get(0).getUserId());

        BeanUtils.copyProperties(userSignin,response);
        BeanUtils.copyProperties(shopInfo.get(0),response);
        response.setAuthority(SigninTypeEnums.shop.getName());
        return response;
    }

    @RequestMapping(value = "signin/userinfo/{userId}",method = {RequestMethod.POST,RequestMethod.PUT})
    @ApiOperation(value = "根据userId修改用户或管理员信息")
    public UserSigninResponse updateInfoByUserId(@ApiParam(value = "请输入nickname")@PathVariable Long userId, @RequestBody UserSigninUpdateRequest request){
        ;
        UserSigninResponse response = new UserSigninResponse();
        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(userId);

        if (userSignin == null){
            log.debug("用户不存在");
            throw new NotFoundException("用户不存在");
        }

        if ( !request.getRepassword().equals(request.getPassword()) ){
            log.debug("密码输入错误");
            throw new ForbiddenException("密码输入错误");
        }

        UserSignin success = new UserSignin();
        BeanUtils.copyProperties(request,success);
        success.setUserId(userId);
        success.setAccount(userSignin.getAccount());
        success.setAuthority(userSignin.getAuthority());
        success.setCreateTime(userSignin.getCreateTime());
        userSigninMapper.updateByPrimaryKey(success);

        if (success.equals(userSignin)){
            log.debug("信息修改失败");
            throw new ForbiddenException("信息修改失败");
        }

        if (success.getAuthority().equals(SigninTypeEnums.user.getValue())){
            response.setAuthority(SigninTypeEnums.user.getName());
        } else if (success.getAuthority().equals(SigninTypeEnums.administrator.getValue())){
            response.setAuthority(SigninTypeEnums.administrator.getName());
        }

        BeanUtils.copyProperties(success,response);
        log.info("response{}",response);
        return response;
    }

    @RequestMapping(value = "signin/shop/{userId}",method = {RequestMethod.POST,RequestMethod.PUT})
    @ApiOperation(value = "根据userId修改商铺信息")
    public ShopSigninResponse updateShopByUserId(@ApiParam(value = "请输入userId")@PathVariable Long userId,@RequestBody ShopInfoUpdateRequest request){

        ShopSigninResponse response = new ShopSigninResponse();
        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(userId);

        ShopInfoExample example = new ShopInfoExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<ShopInfo> shopInfo = shopInfoMapper.selectByExample(example);

        if (userSignin == null || shopInfo.isEmpty()){
            log.debug("商铺不存在");
            throw new NotFoundException("商铺不存在");
        }

        if ( !request.getRepassword().equals(request.getPassword()) ){
            log.debug("密码输入错误");
            throw new ForbiddenException("密码输入错误");
        }

        UserSigninExample example1 = new UserSigninExample();
        example1.createCriteria().andNicknameEqualTo(request.getNickname());
        if ( !userSigninMapper.selectByExample(example1).isEmpty()){
            log.debug("昵称已存在");
            throw new ConflictException("昵称已存在");
        }

        UserSignin success1 = new UserSignin();
        BeanUtils.copyProperties(request,success1);
        ShopInfo success2 = new ShopInfo();
        BeanUtils.copyProperties(request,success2);

        if (success1.equals(userSignin) || success2.equals(shopInfo.get(0))){
            log.debug("信息修改失败");
            throw new ForbiddenException("信息修改失败");
        }

        BeanUtils.copyProperties(success1,response);
        success1.setUserId(userId);
        success1.setAccount(userSignin.getAccount());
        success1.setCreateTime(userSignin.getCreateTime());
        success1.setAuthority(userSignin.getAuthority());
        userSigninMapper.updateByPrimaryKey(success1);

        BeanUtils.copyProperties(success2,response);
        success2.setShopId(shopInfo.get(0).getShopId());
        success2.setUserId(userId);
        response.setAuthority(SigninTypeEnums.shop.getName());
        shopInfoMapper.updateByExample(success2,example);

        response.setShopId(success2.getShopId());
        response.setUserId(userId);
        return response;
    }

    @RequestMapping(value = "signin/userinfo/{userId}",method = RequestMethod.DELETE)
    @ApiOperation(value = "根据userId删除用户或管理员信息")
    public UserSigninResponse deleteInfoByUserId(@ApiParam(value = "请输入userId")@PathVariable Long userId){
        ;
        UserSigninResponse response = new UserSigninResponse();
        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(userId);

        if (userSignin == null){
            log.debug("用户不存在");
            throw new NotFoundException("用户不存在");
        }

        if (userSignin.getAuthority().equals(SigninTypeEnums.user.getValue())){
            response.setAuthority(SigninTypeEnums.user.getName());
        } else if (userSignin.getAuthority().equals(SigninTypeEnums.administrator.getValue())){
            response.setAuthority(SigninTypeEnums.administrator.getName());
        }

        userSigninMapper.deleteByPrimaryKey(userId);
        BeanUtils.copyProperties(userSignin,response);
        return response;
    }

    @RequestMapping(value = "signin/shopinfo/{userId}",method = RequestMethod.DELETE)
    @ApiOperation(value = "根据userId删除商铺信息")
    public ShopSigninResponse deleteShopInfoByUserId(@ApiParam(value = "请输入userId")@PathVariable Long userId){
        ;
        ShopSigninResponse response = new ShopSigninResponse();
        UserSignin userSignin = userSigninMapper.selectByPrimaryKey(userId);
        ShopInfoExample shopInfoExample = new ShopInfoExample();
        shopInfoExample.createCriteria().andUserIdEqualTo(userId);
        List<ShopInfo> shopInfo = shopInfoMapper.selectByExample(shopInfoExample);

        if (userSignin == null){
            log.debug("用户不存在");
            throw new NotFoundException("用户不存在");
        }

        userSigninMapper.deleteByPrimaryKey(userId);
        shopInfoMapper.deleteByExample(shopInfoExample);
        BeanUtils.copyProperties(userSignin,response);
        response.setAuthority(SigninTypeEnums.shop.getName());
        BeanUtils.copyProperties(shopInfo.get(0),response);
        return response;
    }
}
